package com.sec.android.app.myfiles.module.shortcut;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.feature.DlpMgr;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.info.MimeType;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.provider.DbTableInfo;
import com.sec.android.app.myfiles.thumbnail.ThumbnailMgr;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.SemFwWrapper;
import com.sec.android.app.myfiles.util.StorageMonitor;

/**
 * Created by jaebae on 2016-11-23.
 */

public class ShortcutUtils {
    private static final String TAG = "ShortcutUtils";

    private static final String DND_HEADER = "DragAndDropBinding";
    private static final String ITEM_TYPE = "itemType";
    private static final int DND_ITEM_TYPE_SHORTCUT = 1;
    public static final int SHORTCUT_LIMIT_COUNT_FOR_KNOX_DESKTOP = 30;

    private static final String ACTION_INSTALL_SHORTCUT_TO_HOME = "com.android.launcher.action.INSTALL_SHORTCUT";

    public static boolean isSupportShortcut(Context context, FileRecord record) {
        boolean bRet = false;
        if (record != null && record.getFileType() != FileType.UNKNOWN &&
                (record.getStorageType() == FileRecord.StorageType.Local || record.getStorageType() == FileRecord.StorageType.Category || record.getStorageType() == FileRecord.StorageType.Downloads || record.getStorageType() == FileRecord.StorageType.Recent)) {
            if (!DlpMgr.getInstance(context).isDlpFile(record) &&
                    (StorageMonitor.isInternalPath(record.getFullPath()) || StorageMonitor.isMountedSdCardPath(record.getFullPath()))) {
                bRet = true;
            }
        }
        return bRet;
    }

    public static boolean isExistFromShortcut(Context context, FileRecord record) {
        if (record == null || context == null) {
            return false;
        }

        DbTableInfo tableInfo = DbTableInfo.getInstance(FileRecord.StorageType.Shortcut);
        if (tableInfo == null) {
            Log.e(TAG, "onCreateLoader() - DbTableInfo for Shortcut is null");
            return false;
        }

        boolean bRet = false;
        String selection = getSelectionByType(FileRecord.ShortcutType.MyFiles);

        ContentResolver cr = context.getContentResolver();
        if (cr != null) {
            try (Cursor c = cr.query(Uri.parse(tableInfo.getUri()), null, selection, new String[]{record.getFullPath()}, null)) {
                if (c != null && c.getCount() > 0) {
                    bRet = true;
                }
            }
        }
        return bRet;
    }

    public static boolean deleteShortcutFromMyFiles(Context context, FileRecord record) {
        boolean bRet = false;
        ContentResolver cr = context.getContentResolver();
        DbTableInfo tableInfo = DbTableInfo.getInstance(FileRecord.StorageType.Shortcut);
        if (tableInfo != null) {
            String selection = getSelectionByType(FileRecord.ShortcutType.MyFiles);
            int row = cr.delete(Uri.parse(tableInfo.getUri()), selection, new String[]{
                    record.getFullPath()});

            if (row > 0) {
                bRet = true;
                PreferenceUtils.setMyFilesShortcutCount(context, -1);
            }
        }
        return bRet;
    }

    private static Cursor getShortcutCursor(Context context, FileRecord record) {
        DbTableInfo tableInfo = ShortcutDbTableInfo.getInstance();

        ContentResolver cr = context.getContentResolver();
        String selection = getSelectionByType(FileRecord.ShortcutType.HomeScreen);
        String[] args = new String[]{record.getFullPath()};

        return cr.query(Uri.parse(tableInfo.getUri()),
                new String[]{
                        tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH),
                        tableInfo.getColumnName(DbTableInfo.COLUMN_ID.MIME_TYPE)},
                selection, args, null);

    }

    public static void deleteShortcutFromHome(Context context, FileRecord record) {
        DbTableInfo tableInfo = ShortcutDbTableInfo.getInstance();
        if (record != null) {
            try (Cursor cursor = getShortcutCursor(context, record)) {
                if (cursor == null || cursor.getCount() <= 0 || !cursor.moveToFirst()) {
                    return;
                }

                ContentResolver cr = context.getContentResolver();
                String selection = getSelectionByType(FileRecord.ShortcutType.HomeScreen);

                do {
                    String path = cursor.getString(0);
                    String mimeType = cursor.getString(1);

                    if (!TextUtils.isEmpty(path)) {
                        FileRecord shortcutRecord = FileRecord.createFileRecord(record.getStorageType(), path);
                        if (shortcutRecord.getFullPath().equals(record.getFullPath())) {
                            shortcutRecord.setFileType(record.getFileType());
                        } else {
                            shortcutRecord.setFileType(MediaFile.getFileType(path));
                        }
                        shortcutRecord.setMimeType(mimeType);

                        int row = cr.delete(Uri.parse(tableInfo.getUri()), selection, new String[]{path});

                        if (row > 0) {
                            removeHomeScreenShortcut(context, shortcutRecord);
                        }
                    }
                } while (cursor.moveToNext());
            }
        }
    }

    public static void removeHomeScreenShortcut(Context context, FileRecord shortcutRecord) {
        final String ACTION_UNINSTALL_SHORTCUT_IN_HOME = "com.android.launcher.action.UNINSTALL_SHORTCUT";
        Intent pendingIntent = getPendingIntentForShortcut(context, shortcutRecord);
        if (pendingIntent != null) {
            Intent deleteShortcutIntent = new Intent(ACTION_UNINSTALL_SHORTCUT_IN_HOME);
            deleteShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, pendingIntent);
            deleteShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutRecord.getNameWithoutExt());
            context.sendBroadcast(deleteShortcutIntent);
        }
    }

    public static Intent getPendingIntentForShortcut(Context context, FileRecord src) {
        Intent pendingIntent;
        String path = src.getFullPath();
        if (src.isDirectory()) {
            pendingIntent = new Intent(AppConstants.Action.ACTION_LAUNCH_MY_FILES);
            pendingIntent.putExtra(AppConstants.MyFilesExtras.EXTRA_START_PATH, path);
            pendingIntent.putExtra(AppConstants.INTENT_FROM_HOME_SHORTCUT, true);
            pendingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else {
            pendingIntent = new Intent(Intent.ACTION_VIEW);
            int fileType = MediaFile.getFileType(path);
            pendingIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            Uri data = Uri.fromFile(SemFwWrapper.file(path));
            if (fileType == FileType.APK) {
                pendingIntent.setDataAndType(data, MimeType.APK);
            } else if (fileType == FileType.WGT) {
                pendingIntent.setDataAndType(data, MimeType.WIDGET);
            } else {
                pendingIntent.setDataAndType(data, src.getMimeType(context));
            }

            if (fileType == FileType.ZIP) {
                pendingIntent.putExtra(AppConstants.INTENT_KEY_FILE_PATH, path);
            }
        }
        pendingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return pendingIntent;
    }

    public static String getSelectionByType(FileRecord.ShortcutType type) {
        DbTableInfo tableInfo = ShortcutDbTableInfo.getInstance();
        StringBuilder where = new StringBuilder();
        where.append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE)).append('=')
                .append(type.ordinal()).append(" AND (")
                .append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH)).append("=?)");
        return where.toString();
    }

    public static boolean isAddedToShortcut(Context context, FileRecord record, FileRecord.ShortcutType type) {
        boolean bRet = false;
        DbTableInfo tableInfo = DbTableInfo.getInstance(FileRecord.StorageType.Shortcut);
        if (tableInfo != null) {
            String selection = tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH) + "=?" + " AND " + tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE) + "=?";
            String[] selectionArgs = new String[]{
                    record.getFullPath(), Integer.toString(type.ordinal())};
            Uri uri = Uri.parse(tableInfo.getUri());
            try (Cursor c = context.getContentResolver().query(uri, new String[]{"count(*)"}, selection, selectionArgs, null);) {
                if (c.moveToFirst()) {
                    int count = c.getInt(0);
                    if (count > 0) {
                        bRet = true;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception:" + e.toString());
            }
        }
        return bRet;
    }

    public static Intent getIntentForShortcut(Context context, FileRecord record) {
        Intent intent = null;
        if (record != null) {
            intent = new Intent(ACTION_INSTALL_SHORTCUT_TO_HOME);
            Intent pendingIntent = getPendingIntentForShortcut(context, record);
            int thumbnailSize = context.getResources().getDimensionPixelSize(R.dimen.shortcut_icon_thumbnail_size);
            Bitmap shortcutIconBm = ThumbnailMgr.getInstance(context).getHomeShortcutBitmap(context, thumbnailSize, record);
            if (AppFeatures.isKnoxDesktopMode()) {
                intent.putExtra(DND_HEADER, DND_HEADER);
                intent.putExtra(ITEM_TYPE, DND_ITEM_TYPE_SHORTCUT);
                intent.putExtra(AppConstants.INTENT_KEY_FILE_PATH, record.getFullPath());
            }
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, pendingIntent);
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, record.getNameWithoutExt());
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, shortcutIconBm);
        }
        return intent;
    }

    public static int getShortcutItemsCount(Context context) {
        DbTableInfo tableInfo = DbTableInfo.getInstance(FileRecord.StorageType.Shortcut);
        int count = 0;

        if (tableInfo != null) {
            Uri uri = Uri.parse(tableInfo.getUri());
            StringBuilder selection = new StringBuilder();
            selection.append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE)).append('=')
                    .append(FileRecord.ShortcutType.MyFiles.ordinal());
            try (Cursor c = context.getContentResolver().query(uri, null, selection.toString(), null, null)) {
                count = c.getCount();
            } catch (Exception e) {
                Log.e(TAG, "Exception:" + e.toString());
            }
        }

        return count;
    }
}
